<?php

namespace Modules\DataCheck\Jobs;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Modules\DataCheck\Enums\RunModeEnum;
use Modules\DataCheck\Enums\TaskStateEnum;
use Modules\DataCheck\Models\DcTask;
use Modules\DataCheck\Services\DataCheckService;
use Modules\DataCheck\Services\Import\SourceFileImportService;
use Throwable;

/**
 * 数据核对任务
 */
class DataCheckJob implements ShouldQueue
{
    use Queueable;

    public int $timeout = 1800;

    /**
     * 最大尝试次数
     * @var int
     */
    public int $tries = 0;

    public function __construct(private readonly DcTask $task)
    {
    }

    /**
     * @param DataCheckService $service
     * @return void
     */
    public function handle(DataCheckService $service): void
    {
        $service->handle($this->task, RunModeEnum::JOB);
    }

    /**
     * 处理失败作业
     * @param Throwable|null $throwable
     * @return void
     */
    public function failed(?Throwable $throwable): void
    {
        if (empty($throwable)) {
            return;
        }

        $error = [
            'msg' => '数据核对异常',
            'params' => [
                'task_id' => $this->task->task_id,
                'target_file' => $this->task->target_file,
            ],
            'error' => [
                'msg' => $throwable->getMessage(),
                'file' => $throwable->getFile(),
                'line' => $throwable->getLine(),
            ],
        ];

        $update = [
            'task_remark' => json_encode($error, JSON_UNESCAPED_UNICODE),
            'task_state' => TaskStateEnum::FAILED->value,
        ];

        //如果当前是停止状态，核对已停止(核对失败)
        /*$newTask = DcTask::query()->where('task_id', $this->task->task_id)->first();
        if ($newTask->task_state == TaskStateEnum::STOP->value) {
            $update['task_state'] = TaskStateEnum::STOP_CHECK_FAILED->value;
        }*/

        $this->task->update($update);
    }
}